<?php

namespace app\common\model\xilujob;

use app\common\model\User;
use think\Db;
use think\Exception;
use think\Model;
use traits\model\SoftDelete;
use function fast\array_get;


class InterviewComment extends Model
{
    use SoftDelete;
    // 表名
    protected $name = 'xilujob_interview_comment';

    protected $autoWriteTimestamp = 'int';

    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    public function user() {
        return $this->belongsTo(User::class, 'user_id')->setEagerlyType(0);
    }

    public function job() {
        return $this->belongsTo('Job', 'job_id')->setEagerlyType(0);
    }
//
//    public function enterpriseinfo() {
//        return $this->belongsTo('EnterpriseInfo','company_id')->setEagerlyType(0);
//    }

    public static function init() {
        $updateJobScore = function($row) {
            $jobId = $row->job_id;
            $ret = self::where('job_id',$jobId)
                ->fieldRaw('sum(avg_score) as total, count(*) times')
                ->find();
            if($ret && $ret['times']>0) {
                $score = intval($ret['total'] / $ret['times']);
            }else {
                $score = 0;
            }
           Job::where('id',$jobId)->update(['avg_score'=>$score]);
        };
        $updateStatistics = function($row) {
            $commentCount = InterviewComment::where('company_id', $row->company_id)->count();
            CompanyStatistics::where('company_id', $row->company_id)->update([
                'interview_comment_count' => $commentCount
            ]);
        };
        self::afterInsert($updateJobScore);
        self::afterDelete($updateJobScore);
        self::afterInsert($updateStatistics);
        self::afterDelete($updateStatistics);
    }

    public static function addComment($params) {
        $interview = JobInterview::get(array_get($params,'interview_id',0));
        if($interview) {
            if ($interview->user_id != $params['user_id']) {
                throw new Exception(__('no record'));
            }
            $params = array_merge($params, [
                'job_id' => $interview->job_id, 'company_id' => $interview->company_id
            ]);
        }else {
            $job = Job::get(array_get($params,'job_id',0));
            if(!$job) {
                throw new Exception(__('no record'));
            }
            $params = array_merge($params, ['company_id'=>$job->publisher_id,'interview_id'=>0]);
        }
        Db::startTrans();
        try {
            $comment = new static();
            $params['avg_score'] = intval(($params['environment_score']+$params['benefit_score']+$params['opportunity_score'])/3);
            $params['content'] = array_get($params,'content', '');
            $ret = $comment->save($params);
            if ($ret === false) {
                Db::rollback();
                throw new Exception($comment->getError());
            }
            if($interview)
                $interview->save(['has_comment'=>1]);
            Db::commit();
            return $comment;
        }catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }

    }


}
